// 一个简单的不调用X11库的X11客户端示例
// 优化和整理版本 - 专注于核心功能，代码结构清晰

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>
#include <stddef.h>
#include <stdint.h>
#include <sys/types.h>
#include <sys/select.h>
#include <sys/time.h>

// 编译器属性定义
#define _packed __attribute__((packed))

// ================================
// X11 协议结构体定义
// ================================

// X11视觉类型结构体
typedef struct {
    uint32_t visual_id;       // 视觉类型 ID
    uint8_t  class;           // 视觉类（TrueColor=0x4, DirectColor=0x5）
    uint8_t  bits_per_rgb;    // 每个 RGB 分量的位数
    uint16_t colormap_entries;// 颜色映射表条目数
    uint32_t red_mask;        // 红色分量的位掩码
    uint32_t green_mask;      // 绿色分量的位掩码
    uint32_t blue_mask;       // 蓝色分量的位掩码
    uint8_t  pad[4];          // 填充字节
} _packed x11_visual_type;

// X11像素格式结构体
typedef struct {
    uint8_t  depth;              // 颜色深度
    uint8_t  bits_per_pixel;     // 每像素位数
    uint8_t  scanline_pad;       // 扫描线填充位数
    uint8_t  pad[5];             // 填充字节
} _packed x11_pixel_format_type;

// X11颜色深度结构体
typedef struct {
    uint8_t  depth;          // 颜色深度
    uint8_t  pad1;           // 1字节填充
    uint16_t n_visuals;      // 此深度支持的视觉类型数量
    uint32_t pad2;           // 4字节填充
    x11_visual_type visuals[0]; // 可变长度数组，存储视觉类型
} _packed x11_depth_type;

// X11屏幕信息结构体
typedef struct {
    uint32_t root_window;        // 根窗口的 ID
    uint32_t default_colormap;   // 默认颜色映射表 ID
    uint32_t white_pixel;        // 预定义的白色像素值
    uint32_t black_pixel;        // 预定义的黑色像素值
    uint32_t current_input_mask; // 当前输入事件掩码
    uint16_t width_pixels;       // 屏幕宽度（像素）
    uint16_t height_pixels;      // 屏幕高度（像素）
    uint16_t width_millimeters;  // 屏幕物理宽度（毫米）
    uint16_t height_millimeters; // 屏幕物理高度（毫米）
    uint16_t min_installed_maps; // 最小已安装的颜色映射数
    uint16_t max_installed_maps; // 最大已安装的颜色映射数
    uint32_t root_visual;        // 根窗口的视觉类型 ID
    uint8_t  backing_store;      // 是否支持后备存储
    uint8_t  save_unders;        // 是否保存被覆盖窗口的内容
    uint8_t  root_depth;         // 根窗口的颜色深度
    uint8_t  depths_count;       // 支持的深度种类数
    x11_depth_type depths[0];    // 可变长度数组，存储深度信息
} _packed x11_screen_info_type;

// X11连接回复结构体
typedef struct {
    uint8_t  success;            // 固定为 1，表示成功
    uint8_t  pad;                // 填充字节
    uint16_t protocol_major;     // 服务器选择的协议主版本
    uint16_t protocol_minor;     // 服务器选择的协议次版本
    uint16_t additional_length;  // 后续数据的长度（以 4 字节为单位）
    uint32_t release_number;     // 服务器实现的版本号
    uint32_t resource_id_base;   // 资源 ID 的基值
    uint32_t resource_id_mask;   // 资源 ID 的掩码
    uint32_t motion_buffer_size; // 服务器运动事件缓冲区大小
    uint16_t vendor_len;         // 供应商字符串长度
    uint16_t max_request_length; // 客户端请求最大长度
    uint8_t  screens_count;      // 屏幕数量
    uint8_t  formats_count;      // 像素格式数量
    uint8_t  image_byte_order;   // 图像字节序
    uint8_t  bitmap_bit_order;   // 位图位序
    uint8_t  bitmap_scanline_unit; // 位图扫描线单位
    uint8_t  bitmap_scanline_pad;  // 位图扫描线填充位数
    uint8_t  min_keycode;        // 最小键码
    uint8_t  max_keycode;        // 最大键码
    uint8_t  pad2[4];            // 填充字段
} _packed x11_conn_reply_type;

// X11客户端握手请求结构体
typedef struct {
    uint8_t  byte_order;      // 客户端选择的字节顺序
    uint8_t  pad;             // 填充
    uint16_t protocol_major;  // 主版本号
    uint16_t protocol_minor;  // 次版本号
    uint16_t auth_proto_len;  // 认证协议名称长度
    uint16_t auth_data_len;   // 认证数据长度
    uint8_t  pad2[2];         // 填充
} _packed x11_client_request_type;

// 请求结构体
typedef struct {
    uint8_t  opcode;        // 操作码
    uint8_t  data;          // 数据字段
    uint16_t request_length; // 请求长度（单位: 4字节）
} _packed x11_request_header_type;

// CreateWindow 请求核心参数
typedef struct {
    uint32_t window_id;     // 新窗口 ID
    uint32_t parent;        // 父窗口 ID
    int16_t  x;             // X 坐标
    int16_t  y;             // Y 坐标
    uint16_t width;         // 宽度
    uint16_t height;        // 高度
    uint16_t border_width;  // 边框宽度
    uint16_t window_class;  // 窗口类型
    uint32_t visual;        // Visual ID
    uint32_t value_mask;    // 属性掩码
} _packed x11_create_window_core_type;

// X_InternAtom 请求结构
typedef struct {
    uint8_t  opcode;           // 操作码 = 16
    uint8_t  only_if_exists;   // 0=创建, 1=仅当存在时返回
    uint16_t request_length;   // 请求长度(4字节单位)
    uint16_t name_length;      // 原子名称字符串长度
    uint16_t pad;              // 填充字节
} _packed x11_intern_atom_request_type;

// X_InternAtom 响应结构
typedef struct {
    uint8_t  reply_type;       // 1 表示这是一个响应
    uint8_t  pad1;             // 填充字节
    uint16_t sequence_number;  // 序列号
    uint32_t reply_length;     // 额外数据长度
    uint32_t atom;             // 原子ID
    uint8_t  pad2[20];         // 填充字节
} _packed x11_intern_atom_reply_type;

// X_CreateGC 请求结构
typedef struct {
    uint8_t  opcode;           // 操作码 = 55
    uint8_t  pad;              // 填充字节
    uint16_t request_length;   // 请求长度(4字节单位)
    uint32_t gc_id;            // 新建的 GC ID
    uint32_t drawable;         // 可绘制对象 ID
    uint32_t value_mask;       // 属性掩码
} _packed x11_create_gc_request_type;

// X_ImageText8 请求结构
typedef struct {
    uint8_t  opcode;           // 操作码 = 76
    uint8_t  string_length;    // 字符串长度
    uint16_t request_length;   // 请求长度(4字节单位)
    uint32_t drawable;         // 可绘制对象 ID
    uint32_t gc;               // Graphics Context ID
    int16_t  x;                // X 坐标
    int16_t  y;                // Y 坐标
} _packed x11_image_text8_request_type;

// X_ChangeProperty 请求结构
typedef struct {
    uint8_t  opcode;           // 操作码 = 18
    uint8_t  mode;             // 模式 (0=Replace, 1=Prepend, 2=Append)
    uint16_t request_length;   // 请求长度(4字节单位)
    uint32_t window;           // 窗口ID
    uint32_t property;         // 属性原子ID
    uint32_t type;             // 属性类型原子ID
    uint8_t  format;           // 格式 (8, 16, 或 32)
    uint8_t  pad[3];           // 填充字节
    uint32_t data_length;      // 数据长度
} _packed x11_change_property_request_type;

// X11错误响应结构
typedef struct {
    uint8_t  response_type;     // 响应类型 (0表示错误)
    uint8_t  error_type;       // 错误类型
    uint16_t sequence_number;  // 序列号
    uint32_t resource_id;      // 相关资源ID
    uint16_t minor_opcode;     // 次要操作码
    uint8_t  major_opcode;     // 主要操作码
    uint8_t  pad[21];          // 填充字节
} _packed x11_response_error_type;

// ================================
// X11 协议常量定义
// ================================

// 协议版本
#define X_PROTOCOL 11

// 请求操作码
#define X_CreateWindow 1
#define X_MapWindow 8
#define X_ChangeWindowAttributes 2
#define X_ConfigureWindow 12
#define X_InternAtom 16
#define X_ChangeProperty 18
#define X_CreateGC 55
#define X_ImageText8 76
#define X_QueryExtension 98

// 事件掩码
#define ExposureMask        (1L<<15)
#define KeyPressMask        (1L<<0)
#define ButtonPressMask     (1L<<2)
#define StructureNotifyMask (1L<<17)

// 窗口属性掩码
#define CWBackPixel        (1L<<1)
#define CWBorderPixel      (1L<<3)
#define CWEventMask        (1L<<11)

// GC 属性掩码
#define GCForeground       (1L<<2)
#define GCBackground       (1L<<3)

// 事件类型
#define Expose 12
#define KeyPress 2
#define ButtonPress 4
#define ConfigureNotify 22

// ================================
// 全局变量
// ================================

static int x11_socket = -1;
static uint32_t window_id = 0;
static uint32_t root_window = 0;
static uint32_t gc_id = 0;
static char *display_name = NULL;

// 缓存的原子ID
static uint32_t wm_name_atom = 0;
static uint32_t string_atom = 0;

// 函数声明
static int read_x11_auth(char **auth_name, char **auth_data, uint16_t *auth_name_len, uint16_t *auth_data_len);
static void event_loop(void);


// 调试辅助函数 - 打印字节数据
static void print_bytes(const char *title, const void *data, size_t len) {
    printf("%s [%zu bytes]: ", title, len);
    const unsigned char *p = (const unsigned char *)data;
    for (size_t i = 0; i < len && i < 32; i++) {
        printf("%02x ", p[i]);
    }
    if (len > 32) printf("...");
    printf("\n");
}

// 显示帮助信息
static void show_usage(const char *program_name) {
    printf("用法: %s [选项]\n", program_name);
    printf("选项:\n");
    printf("  -display <显示名称>   指定X服务器显示\n");
    printf("                       格式: [主机名]:显示编号[.屏幕编号]\n");
    printf("                       例如: ':0', 'localhost:0', '192.168.1.100:0'\n");
    printf("  -h, --help           显示此帮助信息\n");
}

// 获取事件类型名称
static const char* get_event_name(int event_type) {
    static const char* event_names[] = {
        [0] = "Error", [1] = "Reply", [2] = "KeyPress", [3] = "KeyRelease",
        [4] = "ButtonPress", [5] = "ButtonRelease", [6] = "MotionNotify",
        [7] = "EnterNotify", [8] = "LeaveNotify", [9] = "FocusIn",
        [10] = "FocusOut", [11] = "KeymapNotify", [12] = "Expose",
        [13] = "GraphicsExpose", [14] = "NoExpose", [15] = "VisibilityNotify",
        [16] = "CreateNotify", [17] = "DestroyNotify", [18] = "UnmapNotify",
        [19] = "MapNotify", [20] = "MapRequest", [21] = "ReparentNotify",
        [22] = "ConfigureNotify", [23] = "ConfigureRequest", [24] = "GravityNotify",
        [25] = "ResizeRequest", [26] = "CirculateNotify", [27] = "CirculateRequest",
        [28] = "PropertyNotify", [29] = "SelectionClear", [30] = "SelectionRequest",
        [31] = "SelectionNotify", [32] = "ColormapNotify", [33] = "ClientMessage",
        [34] = "MappingNotify", [35] = "GenericEvent"
    };
    
    if (event_type < 0 || event_type > 35) {
        return "Unknown";
    }
    return event_names[event_type] ? event_names[event_type] : "Unknown";
}

// 获取X11错误类型名称
typedef enum x11_error_type {
    X11_SUCCESS = 0,
    X11_BAD_REQUEST = 1,
    X11_BAD_VALUE = 2,
    X11_BAD_WINDOW = 3,
    X11_BAD_PIXMAP = 4,
    X11_BAD_ATOM = 5,
    X11_BAD_CURSOR = 6,
    X11_BAD_FONT = 7,
    X11_BAD_MATCH = 8,
    X11_BAD_DRAWABLE = 9,
    X11_BAD_ACCESS = 10,
    X11_BAD_ALLOC = 11,
    X11_BAD_COLORMAP = 12,
    X11_BAD_GCONTEXT = 13,
    X11_BAD_ID_CHOICE = 14,
    X11_BAD_NAME = 15,
    X11_BAD_LENGTH = 16,
    X11_BAD_IMPLEMENTATION = 17
} x11_error_type;

static const char* get_x11_error_name(int error_type) {
    static const char* error_names[] = {
        [X11_SUCCESS] = "Success",
        [X11_BAD_REQUEST] = "BadRequest",
        [X11_BAD_VALUE] = "BadValue",
        [X11_BAD_WINDOW] = "BadWindow",
        [X11_BAD_PIXMAP] = "BadPixmap",
        [X11_BAD_ATOM] = "BadAtom",
        [X11_BAD_CURSOR] = "BadCursor",
        [X11_BAD_FONT] = "BadFont",
        [X11_BAD_MATCH] = "BadMatch",
        [X11_BAD_DRAWABLE] = "BadDrawable",
        [X11_BAD_ACCESS] = "BadAccess",
        [X11_BAD_ALLOC] = "BadAlloc",
        [X11_BAD_COLORMAP] = "BadColorMap",
        [X11_BAD_GCONTEXT] = "BadGC",
        [X11_BAD_ID_CHOICE] = "BadIDChoice",
        [X11_BAD_NAME] = "BadName",
        [X11_BAD_LENGTH] = "BadLength",
        [X11_BAD_IMPLEMENTATION] = "ImplementationError"
    };
    
    if (error_type < 0 || error_type > 17) {
        return "Unknown";
    }
    return error_names[error_type] ? error_names[error_type] : "Unknown";
}

// 安全的读取函数
static int safe_read(int fd, void *buf, size_t count) {
    char *ptr = (char*)buf;
    size_t bytes_read = 0;
    
    while (bytes_read < count) {
        ssize_t result = read(fd, ptr + bytes_read, count - bytes_read);
        if (result <= 0) {
            if (result == 0) {
                errno = ECONNRESET;
            }
            return -1;
        }
        bytes_read += result;
    }
    return bytes_read;
}

// 安全的写入函数
static int safe_write(int fd, const void *buf, size_t count) {
    const char *ptr = (const char*)buf;
    size_t bytes_written = 0;
    
    while (bytes_written < count) {
        ssize_t result = write(fd, ptr + bytes_written, count - bytes_written);
        if (result <= 0) {
            return -1;
        }
        bytes_written += result;
    }
    return bytes_written;
}



// 解析X11错误响应
static x11_error_type parse_x11_error(const char *operation_name, const void *data, size_t len) {
    if (len < sizeof(x11_response_error_type)) {
        fprintf(stderr, "错误：数据长度不足以解析X11错误\n");
        return X11_BAD_IMPLEMENTATION;
    }

    x11_response_error_type *error = (x11_response_error_type*)data;
    x11_error_type error_type = X11_SUCCESS;
    if( error->response_type == 0) {
        printf("错误：%s失败\n", operation_name);
        printf("  错误类型: %s (%d)\n", get_x11_error_name(error->error_type), error->error_type);
        printf("  序列号: %d\n", error->sequence_number);
        printf("  资源ID: 0x%x\n", error->resource_id);
        printf("  主要操作码: %d\n", error->major_opcode);
        if (error->minor_opcode != 0) {
            printf("  次要操作码: %d\n", error->minor_opcode);
        }
        error_type = error->error_type;
    } else if (error->response_type == 1) {
        // 这是一个回复响应，而不是错误
        printf("警告：%s收到回复响应而非错误响应\n", operation_name);
        error_type = X11_SUCCESS;
    } else {
        // 这可能是其他类型的响应
        printf("警告：%s收到未知类型的响应 (type=%d)\n", operation_name, error->response_type);
        error_type = X11_SUCCESS;
    }
    
    return error_type;
}

// 检查X11服务器是否返回错误响应
static int check_x11_error(const char *operation_name) {
    // X11协议中，成功的请求通常不会返回响应，但如果有错误会返回错误消息
    // 我们可以通过非阻塞读取来检查是否有错误响应
    fd_set read_fds;
    struct timeval timeout;
    FD_ZERO(&read_fds);
    FD_SET(x11_socket, &read_fds);
    timeout.tv_sec = 0;
    timeout.tv_usec = 100000; // 100ms超时
    
    int select_result = select(x11_socket + 1, &read_fds, NULL, NULL, &timeout);
    if (select_result > 0 && FD_ISSET(x11_socket, &read_fds)) {
        // 有数据可读，可能是错误响应
        uint8_t response[32];
        ssize_t bytes_read = read(x11_socket, response, sizeof(response));
        if (bytes_read > 0) {
            return parse_x11_error(operation_name, response, bytes_read);
        }
    } else if (select_result == -1) {
        perror("错误：检查服务器响应失败");
        return -1;
    }
    
    // 没有错误响应，操作成功
    return 0;
}

// 读取X11认证信息 
static int read_x11_auth(char **auth_name, char **auth_data, uint16_t *auth_name_len, uint16_t *auth_data_len) {
    *auth_name = NULL;
    *auth_data = NULL;
    *auth_name_len = 0;
    *auth_data_len = 0; 
        
    if(!display_name) {
        printf("提示：未指定显示名称，尝试无认证连接\n");
        return 0;
    }

    // 尝试从XAUTHORITY文件或默认位置读取认证信息
    const char *xauth_file = getenv("XAUTHORITY");
    if (!xauth_file) {
        // 默认位置
        const char *home = getenv("HOME");
        if (!home) {
            printf("提示：无法获取HOME目录，尝试无认证连接\n");
            return 0;
        }
        
        static char default_xauth[512];
        snprintf(default_xauth, sizeof(default_xauth), "%s/.Xauthority", home);
        xauth_file = default_xauth;
    }
    
    FILE *fp = fopen(xauth_file, "rb");
    if (!fp) {
        printf("提示：无法打开认证文件 %s，尝试无认证连接\n", xauth_file);
        return 0;
    }
    
    printf("读取X11认证文件: %s\n", xauth_file);
    
    // 解析显示名称以获取主机名和显示编号
    char hostname[256] = "localhost";
    int display_num = 0;
    
    const char *colon = strchr(display_name, ':');
    if (colon) {
        if (colon > display_name) {
            size_t len = colon - display_name;
            if (len < sizeof(hostname)) {
                strncpy(hostname, display_name, len);
                hostname[len] = '\0';
            }
        }
        display_num = atoi(colon + 1);
    }
    
    printf("尝试连接到显示: %s (主机=%s, 显示=%d)\n", display_name, hostname, display_num);
    
    // 获取本机主机名，用于认证匹配
    char localhost_name[256] = "localhost";
    if (gethostname(localhost_name, sizeof(localhost_name)) != 0) {
        strncpy(localhost_name, "localhost", sizeof(localhost_name) - 1);
    }
    localhost_name[sizeof(localhost_name) - 1] = '\0';
    printf("本机主机名: %s\n", localhost_name);
    
    struct {
        char address[256];
        char number[64];
        char name[256];
        char data[256];
        uint16_t addr_len;
        uint16_t num_len;
        uint16_t name_len;
        uint16_t data_len;
    }  record;

    int found = 0;
    
    // 读取Xauthority文件格式
    // 格式：family(2) + address_length(2) + address + number_length(2) + number + name_length(2) + name + data_length(2) + data
    while (!feof(fp) && !found) {
        uint16_t family;
        
        // 读取记录头部
        if (fread(&family, 2, 1, fp) != 1) break;
        if (fread(&record.addr_len, 2, 1, fp) != 1) break;
        
        family = ntohs(family);
        record.addr_len = ntohs(record.addr_len);
        
        // 检查地址长度是否合理
        if (record.addr_len >= sizeof(record.address)) {
            fseek(fp, record.addr_len, SEEK_CUR);
            continue;
        }
        
        // 读取地址
        if (fread(record.address, record.addr_len, 1, fp) != 1) break;
        record.address[record.addr_len] = '\0';
        
        // 读取显示编号
        if (fread(&record.num_len, 2, 1, fp) != 1) break;
        record.num_len = ntohs(record.num_len);
        
        if (record.num_len >= sizeof(record.number)) {
            fseek(fp, record.num_len, SEEK_CUR);
            continue;
        }
        
        if (fread(record.number, record.num_len, 1, fp) != 1) break;
        record.number[record.num_len] = '\0';
        
        // 读取认证协议名称
        if (fread(&record.name_len, 2, 1, fp) != 1) break;
        record.name_len = ntohs(record.name_len);
        
        if (record.name_len >= sizeof(record.name)) {
            fseek(fp, record.name_len, SEEK_CUR);
            continue;
        }
        
        if (fread(record.name, record.name_len, 1, fp) != 1) break;
        record.name[record.name_len] = '\0';
        
        // 读取认证数据
        if (fread(&record.data_len, 2, 1, fp) != 1) break;
        record.data_len = ntohs(record.data_len);
        
        if (record.data_len >= sizeof(record.data)) {
            fseek(fp, record.data_len, SEEK_CUR);
            continue;
        }
        
        if (fread(record.data, record.data_len, 1, fp) != 1) break;
        
        // 检查是否匹配当前显示
        int display_match = (atoi(record.number) == display_num);
        int host_match =
            (strcmp(record.address, hostname) == 0) ||
            (strcmp(record.address, "localhost") == 0) ||
            (strcmp(record.address, localhost_name) == 0) ||
            (record.addr_len == 0) || // unix socket
            1; // 允许任意主机名，只要display编号匹配

        if (display_match && host_match) {
            printf("找到匹配的认证记录: %s:%s, 协议: %s, 数据长度: %d\n", 
                   record.address, record.number, record.name, record.data_len);
            
            // 只在找到匹配记录时才进行内存分配
            *auth_name = malloc(record.name_len + 1);
            *auth_data = malloc(record.data_len);
            
            if (*auth_name && *auth_data) {
                memcpy(*auth_name, record.name, record.name_len);
                (*auth_name)[record.name_len] = '\0';
                memcpy(*auth_data, record.data, record.data_len);
                *auth_name_len = record.name_len;
                *auth_data_len = record.data_len;
                
                // 打印认证数据的十六进制表示
                printf("  认证数据: ");
                for (int j = 0; j < record.data_len; j++) {
                    printf("%02x", (unsigned char)record.data[j]);
                }
                printf("\n");
                
                found = 1;
            } else {
                // 内存分配失败，清理
                if (*auth_name) {
                    free(*auth_name);
                    *auth_name = NULL;
                }
                if (*auth_data) {
                    free(*auth_data);
                    *auth_data = NULL;
                }
                break;
            }
        }
    }
    
    fclose(fp);
    
    if (found) {
        return 1;
    } else {
        printf("提示：未找到匹配的认证记录，尝试无认证连接\n");
        return 0;
    }
}

// 解析显示编号
static int parse_display_number(const char *display_ptr) {
    int display_num = atoi(display_ptr + 1);
    if (display_num < 0 || display_num > 99) {
        fprintf(stderr, "错误：显示编号无效 %d\n", display_num);
        return -1;
    }
    return display_num;
}

// 使用Unix域套接字连接到完整路径
static int connect_unix_socket_path(const char *socket_path) {
    struct sockaddr_un addr;
    
    x11_socket = socket(AF_UNIX, SOCK_STREAM, 0);
    if (x11_socket == -1) {
        perror("错误：创建Unix域套接字失败");
        return -1;
    }
    
    memset(&addr, 0, sizeof(addr));
    addr.sun_family = AF_UNIX;
    
    // 检查路径长度
    if (strlen(socket_path) >= sizeof(addr.sun_path)) {
        fprintf(stderr, "错误：套接字路径过长\n");
        close(x11_socket);
        x11_socket = -1;
        return -1;
    }
    
    strcpy(addr.sun_path, socket_path);
    
    printf("连接到Unix域套接字X服务器: %s\n", addr.sun_path);
    
    if (connect(x11_socket, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
        perror("错误：Unix域套接字连接失败");
        close(x11_socket);
        x11_socket = -1;
        return -1;
    }
    
    return 0;
}

// 使用Unix域套接字连接到标准路径
static int connect_unix_socket_standard(int display_num) {
    struct sockaddr_un addr;
    
    x11_socket = socket(AF_UNIX, SOCK_STREAM, 0);
    if (x11_socket == -1) {
        perror("错误：创建Unix域套接字失败");
        return -1;
    }
    
    memset(&addr, 0, sizeof(addr));
    addr.sun_family = AF_UNIX;
    snprintf(addr.sun_path, sizeof(addr.sun_path), "/tmp/.X11-unix/X%d", display_num);
    
    printf("连接到本地X服务器: %s\n", addr.sun_path);
    
    if (connect(x11_socket, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
        perror("错误：Unix域套接字连接失败");
        close(x11_socket);
        x11_socket = -1;
        return -1;
    }
    
    return 0;
}

// 使用TCP连接
static int connect_tcp_socket(const char *hostname, int display_num) {
    struct sockaddr_in addr;
    struct hostent *host;
    
    printf("连接到X服务器: %s:%d (TCP端口 %d)\n", hostname, display_num, 6000 + display_num);
    
    // 解析主机名
    host = gethostbyname(hostname);
    if (host == NULL) {
        fprintf(stderr, "错误：无法解析主机名 %s\n", hostname);
        return -1;
    }
    
    // 创建TCP套接字
    x11_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (x11_socket == -1) {
        perror("错误：创建TCP套接字失败");
        return -1;
    }
    
    // 设置服务器地址
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(6000 + display_num);
    memcpy(&addr.sin_addr.s_addr, host->h_addr_list[0], host->h_length);
    
    // 连接到服务器
    if (connect(x11_socket, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
        perror("错误：TCP连接失败");
        close(x11_socket);
        x11_socket = -1;
        return -1;
    }
    
    return 0;
}

// 连接到X服务器
static int connect_to_x_server(const char *display_name) {
    if (display_name == NULL) {
        fprintf(stderr, "错误：未指定显示名称\n");
        return -1;
    }
    
    // 情况1：Unix域套接字完整路径格式（如：/private/tmp/com.apple.launchd.xxx/org.xquartz:0）
    if (display_name[0] == '/') {
        const char *display_ptr = strchr(display_name, ':');
        if (display_ptr == NULL) {
            fprintf(stderr, "错误：无效的显示名称格式 '%s'\n", display_name);
            return -1;
        }
        
        // 验证显示编号
        if (parse_display_number(display_ptr) == -1) {
            return -1;
        }
        
        // 使用完整路径连接Unix域套接字
        if (connect_unix_socket_path(display_name) != 0) {
            return -1;
        }
    } else {
        // 情况2：传统显示名称格式（如：:0, localhost:0, hostname:0）
        const char *display_ptr = strchr(display_name, ':');
        if (display_ptr == NULL) {
            fprintf(stderr, "错误：无效的显示名称格式 '%s'\n", display_name);
            return -1;
        }
        
        // 解析显示编号
        int display_num = parse_display_number(display_ptr);
        if (display_num == -1) {
            return -1;
        }
        
        // 解析主机名
        char hostname[256] = {0};
        int is_remote = 0;
        
        if (display_ptr > display_name) {
            // 有主机名部分
            size_t hostname_len = display_ptr - display_name;
            if (hostname_len >= sizeof(hostname)) {
                fprintf(stderr, "错误：主机名过长\n");
                return -1;
            }
            strncpy(hostname, display_name, hostname_len);
            hostname[hostname_len] = '\0';
            is_remote = 1;
        }
        
        // 根据主机名选择连接方式
        if (is_remote || strcmp(hostname, "localhost") == 0) {
            // 远程连接或明确指定localhost时使用TCP
            if (connect_tcp_socket(hostname, display_num) != 0) {
                return -1;
            }
        } else {
            // 本地连接使用标准Unix域套接字路径
            if (connect_unix_socket_standard(display_num) != 0) {
                return -1;
            }
        }
    }
    
    printf("成功连接到X服务器\n");
    return 0;
}

// 执行X11协议握手
static int x11_handshake(void) {
    char *auth_name = NULL;
    char *auth_data = NULL;
    uint16_t auth_name_len = 0;
    uint16_t auth_data_len = 0;
    
    // 尝试读取认证信息
    int has_auth = read_x11_auth(&auth_name, &auth_data, &auth_name_len, &auth_data_len);
    
    // 计算请求总长度（需要4字节对齐）
    uint16_t auth_name_size = ((auth_name_len + 3) / 4) * 4;
    uint16_t auth_data_size = ((auth_data_len + 3) / 4) * 4;
    size_t request_size = sizeof(x11_client_request_type) + auth_name_size + auth_data_size;
    struct x11_handshake_request_type {
        x11_client_request_type header; // 握手请求头
        uint8_t auth[256]; // 认证协议名称和数据
    } _packed request = {
        .header = {
            .byte_order = 'l',         // 小端序
            .pad = 0,
            .protocol_major = X_PROTOCOL,
            .protocol_minor = 0,
            .auth_proto_len = auth_name_len,
            .auth_data_len = auth_data_len,
            .pad2 = {0, 0}
        }
    };

    if(request_size > sizeof(struct x11_handshake_request_type)) {
        fprintf(stderr, "错误：握手请求大小超过最大限制 (%zu > %zu)\n", request_size, sizeof(struct x11_handshake_request_type));
        if (auth_name) free(auth_name);
        if (auth_data) free(auth_data);
        return -1;
    }
   
    // 复制认证数据
    memset(request.auth, 0, sizeof(request.auth));
    if(auth_name_len)
        memcpy(request.auth, auth_name, auth_name_len);
    if(auth_data_len)
        memcpy(request.auth + auth_name_size, auth_data, auth_data_len);
    if (has_auth) {
        printf("发送X11握手请求（使用 %s 认证，长度 %d）\n", auth_name, auth_data_len);
        printf("认证数据: ");
        for (int i = 0; i < auth_data_len; i++) {
            printf("%02x", (unsigned char)auth_data[i]);
        }
        printf("\n");
    } else {
        printf("发送X11握手请求（无认证）\n");
    }
    
    // 发送握手请求
    if (safe_write(x11_socket, &request, request_size) == -1) {
        perror("错误：发送握手请求失败");
        if (auth_name) free(auth_name);
        if (auth_data) free(auth_data);
        return -1;
    }
    
    if (auth_name) free(auth_name);
    if (auth_data) free(auth_data);
    
    // 读取握手响应头
    x11_conn_reply_type response;
    if (safe_read(x11_socket, &response, sizeof(response)) == -1) {
        perror("错误：读取握手响应失败");
        return -1;
    }
    
    if (response.success != 1) {
        fprintf(stderr, "错误：握手失败，状态码: %d\n", response.success);
        if (response.success == 0) {
            // 读取错误信息
            if (response.additional_length > 0) {
                size_t error_len = response.additional_length * 4;
                char *error_msg = malloc(error_len + 1);
                if (error_msg) {
                    if (safe_read(x11_socket, error_msg, error_len) != -1) {
                        error_msg[error_len] = '\0';
                        fprintf(stderr, "服务器错误信息: %s\n", error_msg);
                    }
                    free(error_msg);
                }
            }
        }
        return -1;
    }
    
    printf("握手成功: 协议版本 %d.%d\n", response.protocol_major, response.protocol_minor);
    printf("  服务器版本: %d.%d.%d\n", response.release_number/10000000, (response.release_number / 10000) % 1000/10, response.release_number % 100000/1000); 
    printf("  资源ID基数: 0x%x, 掩码: 0x%x\n", response.resource_id_base, response.resource_id_mask);
    printf("  屏幕数量: %u, 像素格式数量: %u\n", response.screens_count, response.formats_count);
    
    // 跳过供应商字符串
    if (response.vendor_len > 0) {
        size_t vendor_total = ((response.vendor_len + 3) / 4) * 4; // 4字节对齐
        char *vendor_data = malloc(vendor_total);
        if (vendor_data && safe_read(x11_socket, vendor_data, vendor_total) != -1) {
            printf("  供应商: %.*s\n", response.vendor_len, vendor_data);
        }
        free(vendor_data);
    }
    
    // 跳过像素格式数据
    if (response.formats_count > 0) {
        size_t formats_size = response.formats_count * sizeof(x11_pixel_format_type);
        char *formats_data = malloc(formats_size);
        if (formats_data) {
            safe_read(x11_socket, formats_data, formats_size);
        }
        free(formats_data);
    }
    
    // 读取屏幕信息
    if (response.screens_count > 0) {
        x11_screen_info_type screen_info;
        if (safe_read(x11_socket, &screen_info, sizeof(screen_info)) != -1) {
            root_window = screen_info.root_window;
            printf("  屏幕大小: %dx%d 像素\n", screen_info.width_pixels, screen_info.height_pixels);
            printf("  根窗口ID: 0x%x\n", root_window);
            
            // 跳过深度信息
            for (int i = 0; i < screen_info.depths_count; i++) {
                x11_depth_type depth_header;
                if (safe_read(x11_socket, &depth_header, sizeof(depth_header)) != -1) {
                    size_t visuals_size = depth_header.n_visuals * sizeof(x11_visual_type);
                    if (visuals_size > 0) {
                        char *visuals_data = malloc(visuals_size);
                        if (visuals_data) {
                            safe_read(x11_socket, visuals_data, visuals_size);
                        }
                        free(visuals_data);
                    }
                }
            }
        }
    }
    
    // 初始化资源ID
    window_id = response.resource_id_base + 1;
    gc_id = response.resource_id_base + 2;
    
    return 0;
}

// 创建窗口
static int create_window(void) {
    // 构建CreateWindow请求
    size_t request_size = sizeof(x11_request_header_type) + sizeof(x11_create_window_core_type) + 8; // 8字节填充
    struct {
        x11_request_header_type header;
        x11_create_window_core_type core;
        uint32_t back_pixel;
        uint32_t event_mask;
        uint32_t tmp;  //为旧版本兼容增加4字节
    } _packed request = {
        .header = {
            .opcode = X_CreateWindow,
            .data = 0,  // 深度，0表示复制父窗口
            .request_length = request_size / 4,
        },
        .core = {
            .window_id = window_id,
            .parent = root_window,
            .x = 100, .y = 100,
            .width = 400, .height = 300,
            .border_width = 1,
            .window_class = 1,  // InputOutput
            .visual = 0,        // 复制父窗口
            .value_mask = CWBackPixel | CWEventMask
        },
        .back_pixel = 0xFFFFFF,  // 白色背景
        .event_mask = ExposureMask | KeyPressMask | ButtonPressMask | StructureNotifyMask,
        .tmp = 0 // 为旧版本兼容，增加4字节填充
    };
    
    printf("创建窗口 (ID: 0x%x)\n", window_id);
    
    if (safe_write(x11_socket, &request, request_size) == -1) {
        perror("错误：发送创建窗口请求失败");
        return -1;
    }

    // 检查服务器是否返回错误
    if (check_x11_error("创建窗口") == X11_BAD_LENGTH) {
        fprintf(stderr, "错误：创建窗口请求长度不正确，为旧版本X11的兼容性，增加4字节的填充，再试一次\n");
        request.header.request_length += 1; // 增加4字节填充
        request_size += 4; // 更新请求大小
        request.tmp = request.event_mask; // 将事件掩码放入填充字段
        request.event_mask = request.back_pixel;  // 将事件掩码放入填充字段
        if (safe_write(x11_socket, &request, request_size) == -1) {
            perror("错误：发送创建窗口请求失败");
            return -1;
        }
        if (check_x11_error("创建窗口") != 0) {
            return -1;
        }
    }
    
    printf("窗口创建完成\n");
    return 0;
}

// 创建Graphics Context
static int create_gc(void) {
    struct {
        x11_create_gc_request_type header;
        uint32_t foreground;
        uint32_t background;
    } _packed request = {
        .header = {
            .opcode = X_CreateGC,
            .pad = 0,
            .request_length = sizeof(request) / 4,
            .gc_id = gc_id,
            .drawable = window_id,
            .value_mask = GCForeground | GCBackground
        },
        .foreground = 0x000000,  // 黑色前景
        .background = 0xFFFFFF   // 白色背景
    };
    
    printf("创建Graphics Context (ID: 0x%x)\n", gc_id);
    
    if (safe_write(x11_socket, &request, sizeof(request)) == -1) {
        perror("错误：发送创建GC请求失败");
        return -1;
    }
    
    // 检查服务器是否返回错误
    if (check_x11_error("创建Graphics Context") != 0) {
        return -1;
    }
    
    printf("Graphics Context创建完成\n");
    return 0;
}

// 查询原子ID
static int intern_atom(const char *atom_name, uint32_t *atom_id) {
    if (!atom_name || !atom_id) {
        fprintf(stderr, "错误：无效的参数\n");
        return -1;
    }
    
    size_t name_len = strlen(atom_name);
    if (name_len == 0 || name_len > 255) {
        fprintf(stderr, "错误：原子名称长度无效 (%zu)\n", name_len);
        return -1;
    }
    
    size_t request_size = sizeof(x11_intern_atom_request_type) + ((name_len + 3) / 4) * 4; // 4字节对齐
    // 构建 InternAtom 请求
    struct {
        x11_intern_atom_request_type header;
        char name[256];  // 足够大的缓冲区
    } _packed request = {
        .header = {
            .opcode = X_InternAtom,
            .only_if_exists = 0,  // 如果不存在则创建
            .request_length = request_size / 4, // 请求长度（4字节单位）
            .name_length = name_len,
            .pad = 0
        },
    };
    memset(request.name , 0, sizeof(request.name));
    memcpy(request.name, atom_name, name_len);

    // 发送请求
    if (safe_write(x11_socket, &request, request_size) == -1) {
        perror("错误：发送原子查询请求失败");
        return -1;
    }
    
    // 读取响应
    x11_intern_atom_reply_type response;
    if (safe_read(x11_socket, &response, sizeof(response)) == -1) {
        perror("错误：读取原子查询响应失败");
        return -1;
    }
    
    if (response.reply_type != 1) {
        fprintf(stderr, "错误：原子查询响应无效 (类型=%d)\n", response.reply_type);
        return -1;
    }
    
    *atom_id = response.atom;
    return 0;
}

// 设置窗口标题
static int set_window_title(const char *title) {
    if (!title) {
        fprintf(stderr, "错误：标题不能为空\n");
        return -1;
    }
    
    size_t title_len = strlen(title);
    if (title_len == 0) {
        fprintf(stderr, "错误：标题长度不能为0\n");
        return -1;
    }
    
    // 如果还未缓存原子，则查询
    if (wm_name_atom == 0) {
        if (intern_atom("WM_NAME", &wm_name_atom) != 0) {
            return -1;
        }
    }
    
    if (string_atom == 0) {
        if (intern_atom("STRING", &string_atom) != 0) {
            return -1;
        }
    }
    
    size_t request_size = 24 + ((title_len + 3) / 4) * 4; // 4字节对齐
    // 构建 ChangeProperty 请求
    struct {
        x11_change_property_request_type header;
        char title_data[512];  // 足够大的缓冲区
    } _packed request = {
        .header = {
            .opcode = X_ChangeProperty,
            .mode = 0,  // 替换模式
            .request_length = request_size / 4, // 请求长度（4字节单位）
            .window = window_id,
            .property = wm_name_atom,
            .type = string_atom,
            .format = 8,  // 8位格式
            .data_length = title_len
        }
    };

    if (request_size > sizeof(request)) {
        fprintf(stderr, "错误：标题过长 (%zu > %zu)\n", title_len, sizeof(request.title_data));
        return -1;
    }
    
    memset(request.title_data, 0, sizeof(request.title_data));
    memcpy(request.title_data, title, title_len);
    
    // 发送请求
    if (safe_write(x11_socket, &request, request_size) == -1) {
        perror("错误：设置窗口标题失败");
        return -1;
    }
    
    // 检查服务器是否返回错误
    if (check_x11_error("设置窗口标题") != 0) {
        return -1;
    }
    
    printf("设置窗口标题: %s\n", title);
    return 0;
}

// 绘制字符串 - 优化版本
static int draw_string(int x, int y, const char *str) {
    if (!str) {
        fprintf(stderr, "错误：字符串不能为空\n");
        return -1;
    }
    
    size_t str_len = strlen(str);
    if (str_len == 0) {
        return 0;  // 空字符串，直接返回成功
    }
    
    if (str_len > 255) {
        fprintf(stderr, "错误：字符串过长 (%zu > 255)\n", str_len);
        return -1;
    }
    
    // 计算4字节对齐的请求大小
    size_t request_size = sizeof(x11_image_text8_request_type) +  ((str_len + 3) / 4) * 4;

    // 绘制字符串的优化结构
    struct {
        x11_image_text8_request_type header;
        char text_data[256];  // 最大字符串长度 + 填充
    } _packed request = {
        .header = {
            .opcode = X_ImageText8,
            .string_length = (uint8_t)str_len,
            .request_length = request_size / 4,
            .drawable = window_id,
            .gc = gc_id,
            .x = (int16_t)x,
            .y = (int16_t)y
        }
    };
    
    // 清零并复制字符串数据
    memset(request.text_data, 0, sizeof(request.text_data));
    memcpy(request.text_data, str, str_len);
    
    // 发送请求
    if (safe_write(x11_socket, &request, request_size) == -1) {
        perror("错误：绘制字符串失败");
        return -1;
    }
    
    // 检查服务器是否返回错误
    //if (check_x11_error("绘制字符串") != 0) {
    //    return -1;
    //}
    
    return 0;
}

// 映射窗口
static int map_window(void) {
    struct {
        uint8_t opcode;
        uint8_t pad;
        uint16_t request_length;
        uint32_t window;
    } _packed request = {
        .opcode = X_MapWindow,
        .pad = 0,
        .request_length = 2,
        .window = window_id
    };
    
    printf("映射窗口到屏幕\n");
    
    if (safe_write(x11_socket, &request, sizeof(request)) == -1) {
        perror("错误：映射窗口失败");
        return -1;
    }
    
    // 检查服务器是否返回错误
    if (check_x11_error("映射窗口") != 0) {
        return -1;
    }
    
    printf("窗口映射完成\n");
    return 0;
}

// 事件循环
static void event_loop(void) {
    uint8_t event[32];
    
    printf("进入事件循环，按ESC键退出\n");
    
    while (1) {
        int bytes = read(x11_socket, event, sizeof(event));
        if (bytes <= 0) {
            if (bytes == 0) {
                printf("X服务器关闭了连接\n");
            } else {
                perror("读取事件失败");
            }
            break;
        }
        
        uint8_t event_type = event[0] & 0x7F;
        printf("收到事件: %s (类型=%d)\n", get_event_name(event_type), event_type);
        
        switch (event_type) {
            case Expose:
                printf("窗口需要重绘\n");
                draw_string(50, 50, "Hello X11!");
                draw_string(50, 80, "This is an X11 Sample Raw Client");
                draw_string(50, 110, "Press ESC to exit");
                break;
                
            case KeyPress: {
                uint8_t keycode = event[1];
                printf("Key event: keycode=%d\n", keycode);
                
                // ESC键退出
                if (keycode == 9) {
                    printf("ESC key detected, exiting program\n");
                    return;
                }
                break;
            }
            
            case ButtonPress: {
                uint8_t button = event[1];
                int16_t x = *(int16_t*)(event + 24);
                int16_t y = *(int16_t*)(event + 26);
                printf("Mouse click: button=%d, position=(%d, %d)\n", button, x, y);
                break;
            }
            
            case ConfigureNotify: {
                int16_t x = *(int16_t*)(event + 16);
                int16_t y = *(int16_t*)(event + 18);
                uint16_t width = *(uint16_t*)(event + 20);
                uint16_t height = *(uint16_t*)(event + 22);
                printf("Window configuration changed: position=(%d, %d), size=%dx%d\n", x, y, width, height);
                break;
            }
        }
        
        usleep(10000); // 10ms延迟
    }
}

// ================================
// 主函数
// ================================

int main(int argc, char *argv[]) {
    // 解析命令行参数
    for (int i = 1; i < argc; i++) {
        if (strcmp(argv[i], "-display") == 0 && i + 1 < argc) {
            display_name = argv[i + 1];
            i++;
        } else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) {
            show_usage(argv[0]);
            return 0;
        } else {
            fprintf(stderr, "Error: Unknown option '%s'\n", argv[i]);
            show_usage(argv[0]);
            return 1;
        }
    }

    if (!display_name || strlen(display_name) == 0) {
        display_name = getenv("DISPLAY");
        if (display_name && strlen(display_name) > 0) {
            printf("Using DISPLAY environment variable: %s\n", display_name);
        } else {
            printf("Note: No display name specified and DISPLAY environment variable not set, using default display ':0'\n");
            display_name = ":0";
        }
    }
    
    
    // 连接到X服务器
    if (connect_to_x_server(display_name) != 0) {
        return 1;
    }
    
    // 执行握手
    if (x11_handshake() != 0) {
        close(x11_socket);
        return 1;
    }
    
    // 创建窗口
    if (create_window() != 0) {
        close(x11_socket);
        return 1;
    }
    
    // 创建Graphics Context
    if (create_gc() != 0) {
        close(x11_socket);
        return 1;
    }
    
    // 设置窗口标题
    if (set_window_title("X11 Sample Raw Client") != 0) {
        close(x11_socket);
        return 1;
    }
    
    // 映射窗口
    if (map_window() != 0) {
        close(x11_socket);
        return 1;
    }
    
    // 进入事件循环
    event_loop();
    
    // 清理资源
    close(x11_socket);
    printf("Program exited normally\n");
    return 0;
}
